package top.hjcwzx.wrench.limiter.utils;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class IpUtil {

    /**
     * 获取客户端真实 IP 地址，考虑了多级代理情况
     * @return IP 字符串，若无法获取则返回 "unknown"
     */
    public static String getClientIp() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            return "unknown";
        }

        HttpServletRequest request = attrs.getRequest();
        String ip = getHeaderIp(request, "X-Forwarded-For");
        if (ip == null) ip = getHeaderIp(request, "Proxy-Client-IP");
        if (ip == null) ip = getHeaderIp(request, "WL-Proxy-Client-IP");
        if (ip == null) ip = getHeaderIp(request, "HTTP_CLIENT_IP");
        if (ip == null) ip = getHeaderIp(request, "HTTP_X_FORWARDED_FOR");
        if (ip == null) ip = request.getRemoteAddr();

        return ip;
    }

    private static String getHeaderIp(HttpServletRequest request, String header) {
        String ip = request.getHeader(header);
        if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
            // 有些 header 是多个 IP 的链表
            return ip.split(",")[0].trim();
        }
        return null;
    }
}
